package oa.hleast.xswl.controller.app;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.redis.component.template.RedisRepository;
import oa.hleast.common.result.Result;
import oa.hleast.common.result.ResultCode;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.common.web.util.RequestUtils;
import oa.hleast.xswl.common.annotation.UserAuth;
import oa.hleast.xswl.common.util.BaiduUtils;
import oa.hleast.xswl.pojo.domain.SysDict;
import oa.hleast.xswl.pojo.domain.UmsMember;
import oa.hleast.xswl.pojo.dto.ManagerUserDTO;
import oa.hleast.xswl.pojo.dto.MemberDataDTO;
import oa.hleast.xswl.pojo.form.BaseUmsUserForm;
import oa.hleast.xswl.pojo.vo.IdCardVO;
import oa.hleast.xswl.pojo.vo.MemberVO;
import oa.hleast.xswl.service.IUmsUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Api(tags = "【移动端】会员服务")
@RestController
@RequestMapping("/api.app/v1/users")
@Slf4j
@AllArgsConstructor
public class MemberController {

    private final IUmsUserService iUmsUserService;
    private final RedisRepository redisRepository;


    @UserAuth
    @ApiOperation(value = "获取当前请求的会员信息", httpMethod = "GET")
    @GetMapping("/me")
    public Result<MemberVO> getMemberInfo() {
        Long userId = RequestUtils.getUserId();
        log.info("userId = {}",userId);
        UmsMember user = iUmsUserService.getById(userId);
        if (user == null) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }
        MemberVO memberVO = new MemberVO();
        BeanUtil.copyProperties(user, memberVO);
        return Result.success(memberVO);
    }

    @UserAuth
    @ApiOperation(value = "实名认证", httpMethod = "POST")
    @PostMapping("/bindIdCard")
    public Result bindIdCard(@RequestBody IdCardVO idCardVO) {
        log.info("idCardVO = {}", idCardVO);
        Long userId = RequestUtils.getUserId();
        UmsMember user = iUmsUserService.getById(userId);
        if (user == null) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }

        if (0 == user.getAuthStatus()) {
            return Result.failed(ResultCode.USER_NOT_PHONE);
        }
        Map<String, String> idCardInfo = null;
        try {
            idCardInfo = BaiduUtils.checkIdCard(idCardVO);
        } catch (Exception e) {
            throw new BizException("信息不合法" + e.getMessage());
        }
        log.info("idCardInfo = {}", idCardInfo);
        // 更新身份证信息
        BeanUtil.copyProperties(idCardVO, user);
        user.setAuthStatus(2);
        user.setFullname(idCardInfo.get("name"));
        user.setIdCardNum(idCardInfo.get("idNum"));
        List<SysDict> dicts = iUmsUserService.getGenderDict();
        log.info("dicts = {}", dicts);
        try {
            String gender = idCardInfo.get("gender");
            for (SysDict dict : dicts) {
                log.info("dict = {},isEquals = {}", dict, dict.getName().equals(gender));
                if (dict.getName().equals(gender)) {
                    user.setGender(dict.getId().intValue());
                    break;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate brithday = LocalDate.parse(idCardInfo.get("brithday"), fmt);
        user.setBirthday(brithday);
        log.info("实名认证 ,user = {}", user);
        boolean update = iUmsUserService.updateById(user);

        return Result.success(update);
    }

    @UserAuth
    @ApiOperation(value = "绑定手机", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "uuid", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "type", value = "用户类型 0: 应聘者 1: HR 2: 面试官", required = false, defaultValue = "0", paramType = "query", dataType = "Integer", dataTypeClass = Integer.class)
    })
    @PostMapping("/bindPhone")
    public Result bindPhone(String uuid, String name, String phone, String code, @RequestParam(name = "type", defaultValue = "0", required = false) Integer type) {
        log.info("uuid  = {} ,name = {} ,phone = {} ,code = {}, type = {}", uuid, name, phone, code, type);
        Long userId = RequestUtils.getUserId();
        UmsMember user = iUmsUserService.getById(userId);
        if (user == null) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }

        if (checkPhone(uuid, phone, code)) {
            // 更新用户手机号
            user.setFullname(name);
            user.setMobile(phone);
            user.setAuthStatus(1);
            user.setType(type);
            boolean update = iUmsUserService.updateById(user);
            return Result.success(update);
        }

        return Result.success(false);

    }

    private boolean checkPhone(String uuid, String phone, String code) {
        boolean isPhone = PhoneUtil.isPhone(phone);
        String cacheCode = redisRepository.get(uuid + ":" + phone) + "";
        if (StrUtil.isEmpty(cacheCode)) {
            throw new BizException("您的验证码已过期,请重新获取");
        }
        log.info("cache = {},code = {}", cacheCode, cacheCode);
        if (!cacheCode.equals(code)) {
            throw new BizException("验证码错误");
        }
        return isPhone;
    }


    @ApiOperation(value = "发送验证码", httpMethod = "GET")
    @GetMapping("/sendSms")
    public Result sendSms(@RequestParam String phone) {
        log.info("phone = {}", phone);
        Long userId = RequestUtils.getUserId();
        log.info("userId = {}",userId);
        UmsMember user = iUmsUserService.getById(userId);
        if (user == null) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }
        try {
            String uuid = iUmsUserService.sendSms(phone);

            return Result.success(uuid);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }

    }


    @UserAuth
    @ApiOperation(value = "修改会员【基础信息】", httpMethod = "POST")
    @ApiImplicitParam(name = "form", value = "实体JSON对象", required = true, paramType = "body", dataType = "BaseUmsUserForm", dataTypeClass = BaseUmsUserForm.class)
    @PostMapping(value = "/updateBaseUserInfo")
    public Result updateBaseUserInfo(@RequestBody BaseUmsUserForm form) {
        Long userId = RequestUtils.getUserId();
        LambdaUpdateWrapper<UmsMember> updateWrapper = new LambdaUpdateWrapper<UmsMember>().eq(UmsMember::getId, userId);
        updateWrapper.set(form.getAvatar() != null, UmsMember::getAvatar, form.getAvatar());
        updateWrapper.set(form.getMobile() != null, UmsMember::getUsername, form.getMobile());
        updateWrapper.set(form.getNickname() != null, UmsMember::getNickname, form.getNickname());

        boolean status = iUmsUserService.update(updateWrapper);
        return Result.judge(status);
    }

    /**
     * 获取面试官列表
     */
    @ApiOperation(value = "获取面试官列表", httpMethod = "GET")
    @GetMapping("/findInterviewer")
    public Result<List<UmsMember>> findInterviewer() {

        List<UmsMember> list = iUmsUserService.findInterviewer();

        return Result.success(list);
    }


    @ApiOperation(value = "手动切换用户类型", httpMethod = "GET")
    @GetMapping("/updateUserType")
    public Result<Integer> updateUserType(@RequestParam Integer type) {
        // TODO  此接口仅供测试使用使用后要删除
        Long userId = RequestUtils.getUserId();
        boolean update = iUmsUserService.update(new LambdaUpdateWrapper<UmsMember>()
                .set(UmsMember::getType, type)
                .eq(UmsMember::getId, userId)
        );

        Integer updateType = iUmsUserService.getById(userId).getType();

        return Result.success(updateType);
    }

    @ApiOperation(value = "获取会员用户的积分-需要带token", httpMethod = "GET")
    @GetMapping("/getPoint")
    public Result<Long> getPoint() {

        Long userId = RequestUtils.getUserId();
        Long point = iUmsUserService.getPoint(userId);


        return Result.success(point);
    }

    @ApiOperation(value = "个人中心用户信息 -token", httpMethod = "GET")
    @GetMapping("/getMemberByToken")
    public Result<MemberDataDTO> getMemberByToken() {
        Long userId = RequestUtils.getUserId();
        MemberDataDTO dto = iUmsUserService.getMemberByToken(userId);
        if (ObjectUtils.isEmpty(dto)) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }
        return Result.success(dto);
    }


    @ApiOperation(value = "用户基础信息", httpMethod = "GET")
    @GetMapping("/getBaseMember")
    public Result<ManagerUserDTO> getBaseMember() {
        Long userId = RequestUtils.getUserId();
        ManagerUserDTO dto = iUmsUserService.getBaseMember(userId);
        if (ObjectUtils.isEmpty(dto)) {
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }
        return Result.success(dto);
    }

}
